<template>
	<view>
		<!-- 搜索栏区域 -->
		<view class="search-box-wrapper">
			<view class="search-title">
				<!-- {{applicationConfig.applicationName}} -->
				<text @click="showCate = !showCate" class="iconfont icon-more"></text>
			</view>
			<view class="wrapper">
				<search-box></search-box>
			</view>
			
		</view>
		<view class="content">
			<!-- <scroll-view scroll-y class="left-aside" :class="{'show':showCate,'hide':!showCate}"> -->
			<view class="left-aside" :class="{'show':showCate,'hide':!showCate}">
				<view class="cate-list">
				<view v-for="item in cateList" :key="item.resourceCateUuid" class="f-item b-b"
					:class="{active: item.resourceCateUuid === selectedResourceCate.resourceCateUuid}"
					@click="resourceCateTap(item)">
					<img :src="item.catePicUrl" alt="">{{item.cateName}}
				</view>
				</view>
			</view>
			<!-- </scroll-view> -->
			<view class="right-aside">
				<view id="nav-bar" class="nav-bar custom-nav-bar">
					<view v-for="(item,index) in tabBars" :key="item.value" class="nav-item"
						:class="{current: index === tabCurrentIndex}" :id="'tab'+index" @click="changeTab(index)">
						{{item.name}}
					</view>
				</view>
				<swiper class="swiper-box" :style="{height: swiperHeight+'px'}" :duration="300" :current="tabCurrentIndex" @change="changeTab">
					<swiper-item v-for="(tabItem,index) in tabBars" :key="tabItem.value">
						<view :class="'swiper-item-'+index">
						<!-- <scroll-view class="panel-scroll-box" scroll-with-animation scroll-y @scrolltolower="loadMore(selectedResourceCate,tabItem)"> -->
							<resource-list :resourceList="tabItem.resourceList" :cols="1"></resource-list>
							<uni-load-more :status="tabItem.loadMoreStatus"></uni-load-more>
						<!-- </scroll-view> -->
						</view>
					</swiper-item>
				</swiper>
			</view>
		</view>
	</view>
</template>

<script>
	import resourceList from '@/components/resource-list.vue'
	import searchBox from '@/components/search-box.vue'


	import {
		mapState,
		mapMutations
	} from 'vuex';
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			searchBox,
			resourceList
		},
		data() {
			return {
				searchKey: "",
				showCate: true,
				cateList: [], //资源类目
				selectedResourceCate: {}, //选中的资源类目
				selectedResourceType: '', //选中的资源类型
				resourceList: [], //资源列表
				resource: {},
				tabBars: [{
					name: '全部',
					value: '0',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false

				}, {
					name: '文章',
					value: '1',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false

				}, {
					name: '音频',
					value: '2',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}, {
					name: '视频',
					value: '3',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}, {
					name: '电子书',
					value: '4',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}],
				swiperHeight:0,	//swiper的动态高度
				tabCurrentIndex: 0, //当前选项卡索引
				pageSize: 6,
				pageNo: 1
			}
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint',
				'applicationConfig'
			])
		},
		onLoad(option) {
			// 获取屏幕高度
			uni.getSystemInfo({
				success(res) {
					var winHeight = res.windowHeight;
				}
			})
			this.selectedResourceCate.resourceCateUuid = option.cateId;
			this.inquiryResourceCate();
		},
		onReachBottom(){
			this.loadMore(this.selectedResourceCate,this.tabBars[this.tabCurrentIndex]);
		},
		methods: {
			...mapMutations([]),
			setSearchKey(searchKey) {
				this.searchKey = searchKey;
			},
			inquiryResourceCate() {
				let that = this;
				that.$api.request.inquiryResourceCate({}, res => {
					if (res.body.status.statusCode === '0') {
						that.cateList = res.body.data.cates;
						//默认选中
						if (that.cateList.length > 0) {
							if (that.selectedResourceCate.resourceCateUuid) {
								/* 页面参数指定默认分类, 循环找到该分类并触发点击 */
								that.cateList.forEach(function(item, index) {
									if (item.resourceCateUuid == that.selectedResourceCate
										.resourceCateUuid) {
										that.resourceCateTap(item);
									}
								})
							} else that.resourceCateTap(that.cateList[0]);
						}
					} else {
						console.log(res.body.status.errorDesc);
					}
				}, true);
			},
			//分类点击
			resourceCateTap(resourceCate) {
				this.selectedResourceCate = resourceCate;
				//重置tabbar数据
				this.resetTabBar();


				//默认选项卡第一个位置
				this.tabCurrentIndex = 0;
				let tabItem = this.tabBars[this.tabCurrentIndex];
				this.loadResource(resourceCate, tabItem);
			},
			//分页查询资源
			prepareSearchResource(resourceCate, tabItem) {
				tabItem.loadMoreStatus = 'loading';
				var keyArray = [];
				keyArray.push('IS_PUBLISHED');
				keyArray.push('RESOURCE_CATE');
				//非全部显示, 指定资源类型查询条件
				if (this.tabCurrentIndex != 0)
					keyArray.push('RESOURCE_TYPE');
				let searchData = {
					'keyArray': keyArray,
					'published': true,
					'resourceCateUuid': resourceCate.resourceCateUuid,
					'resourceType': tabItem.value,
					'startIndex': (tabItem.pageNo - 1) * this.pageSize,
					'pageSize': this.pageSize,
				};
				return searchData;
			},
			//加载更多资源
			loadMore(resourceCate, tabItem) {
				//如果已经加载完成则直接返回
				if (tabItem.loadMoreStatus === 'noMore') {
					return;
				}
				tabItem.pageNo = tabItem.pageNo + 1;
				let searchData = this.prepareSearchResource(resourceCate, tabItem);
				this.searchResource(searchData, function(resourceList, total) {
					tabItem.resourceList = tabItem.resourceList.concat(resourceList);
					tabItem.loadMoreStatus = tabItem.resourceList.length >= total ? 'noMore' : 'more';
				});

			},
			loadResource(resourceCate, tabItem) {
				//如果已经加载完成则直接返回
				if (tabItem.loadMoreStatus === 'noMore') {
					return;
				}
				let searchData = this.prepareSearchResource(resourceCate, tabItem);
				this.searchResource(searchData, function(resourceList, total) {
					tabItem.resourceList = tabItem.resourceList.concat(resourceList);
					tabItem.loadMoreStatus = tabItem.resourceList.length >= total ? 'noMore' : 'more';
				});

			},
			searchResource(searchData, callback) {
				let that = this;
				that.$api.request.searchResource(searchData, res => {
					if (res.body.status.statusCode === '0') {
						let total = res.body.data.total;
						let resourceList = res.body.data.resourceList;
						callback(resourceList, total);
					} else {
						console.log(res.body.status.errorDesc);
					}
					this.$nextTick(() => {
						this.setSwiperHeight();
					});
				}, true);
			},
			//重置页码
			resetTabBar() {
				this.tabBars.forEach(function(tabItem, index) {
					tabItem.pageNo = 1;
					tabItem.resourceList = [];
					tabItem.loadMoreStatus = 'more',
						tabItem.loaded = false;
				});
			},
			navToDetailPage(item) {
				let id = item.resourceUuid;
				uni.navigateTo({
					url: '/pages/resource/resource?id=' + id
				})
			},
			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadResource(this.selectedResourceCate, tabItem);
						tabItem.loaded = true;
					}else{
						this.setSwiperHeight();
					}
				}, 300)
			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			/* 动态设置siper的高度, swiper组件是固定高度, 如果在swiper-item里面使用scroll-view, 又会造成页面有两个滚动盒,造成用户体验不好 */
			setSwiperHeight(){
				let that = this;
				let element = '.swiper-item-'+this.tabCurrentIndex;
				let query = uni.createSelectorQuery().in(that);
				query.selectAll(element).boundingClientRect();
				query.exec((res) => {
					if(res && res[0] && res[0][0]) {
						that.swiperHeight = res[0][0].height;
					}
				});
			}
		}
	}
</script>

<style lang='scss'>
	page {
		background: $bg-color-light;
	}

	.content {
		height: 100%;
	}

	.search-box-wrapper {
		display: flex;
		margin: $page-row-spacing;
		align-items: center;
		.wrapper{
			width: 100%;
		}
		.search-title {
			margin-right: 10upx;
			width: 200upx;
			height: 80upx;
			line-height: 80upx;
			text-align: center;
			color: $font-color-dark;
			font-size: $font-lg;
			font-weight: bold;
			overflow: hidden;

			.iconfont {
				font-size: $font-lg+30upx;
			}

			.cate {
				margin-left: 10upx;
				font-size: $font-base;
				color: #fff;
			}
		}

	}
	
	.content {
		display: flex;
	}

	.left-aside {
		flex-shrink: 0;
		width: 200upx;
		.cate-list{
			position: sticky;
			top: var(--window-top);
		}
	}

	.f-item {
		display: flex;
		align-items: center;
		justify-content: left;
		padding-left: 15upx;
		width: 100%;
		height: 100upx;
		font-size: $font-base;
		color: $font-color-base;
		position: relative;

		img {
			width: 50upx;
			height: 50upx;
			margin-right: 10upx;
		}

		&.active {
			color: #fff;
			font-size: $font-lg;
			font-weight: bold;
			background: $bg-color-dark;
		}
	}

	.right-aside {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding-bottom: 120upx;
		margin: 0 20upx;
		.top {
			flex: 0;

			.title {
				background: #fff;
				font-size: 26upx;
				color: $font-color-dark;
				font-weight: bold;
				margin-top: 10px;
				padding: 10px 0 0 10px;
			}
		}

		.center {
			flex: 1
		}
	}

	.custom-nav-bar {
		position: relative;
		/* position: sticky;
		top: var(--window-top); */
	}

	.swiper-box {
		min-height: 150px;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	.show {
		animation: slideContentRight 0.3s linear both;
	}

	.hide {
		animation: slideContentLeft 0.3s linear both;
	}

	@keyframes slideContentRight {
		from {
			margin-left: -200upx;
		}

		to {
			margin-left: 0;
		}
	}

	@keyframes slideContentLeft {
		from {
			margin-left: 0;
		}

		to {
			margin-left: -200upx;
		}
	}
</style>